/*
 * Copyright (C) 2015 yixun All Rights Reserved.
 * 
 * AreaServiceImpl.java
 */
package com.yixun.qfbao.api.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yixun.common.page.Page;
import com.yixun.common.page.PageUtil;
import com.yixun.qfbao.api.service.DataPermissionService;
import com.yixun.qfbao.api.service.DeptPermissionService;
import com.yixun.qfbao.api.service.OrganizationService;
import com.yixun.qfbao.apidto.ZNodes;
import com.yixun.qfbao.apidto.*;
import com.yixun.qfbao.dao.DepartmentDao;
import com.yixun.qfbao.mapper.DepartmentMapper;
import com.yixun.qfbao.mapper.PartnerInfoMapper;
import com.yixun.qfbao.model.*;
import com.yixun.qfbao.model.dto.*;
import com.yixun.qfbao.model.enums.*;
import com.yixun.qfbao.service.*;
import com.yixun.qfbao.util.RegexUtil;
import com.yixun.qfbao.util.StringUtil;
import com.yixun.qfbao.util.exception.TServerException;
import com.yixun.qfbao.xf.model.Premises;
import com.yixun.qfbao.xf.model.dto.PremisesDto;
import com.yixun.qfbao.xf.model.enums.ResultEnum;
import com.yixun.qfbao.xf.service.PremisesService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * [文件名称]<br>
 * LoginServiceImpl.java<br>
 * <br>
 * [文件描述]<br>
 * 登录、退出相关<br>
 * <br>
 * 
 * @author JHSong
 * @version 1.00
 */
@Slf4j
@Service
public class OrganizationServiceImpl implements OrganizationService {
	
	@Autowired
	private DepartmentDao departmentDao;
	@Autowired
	private CompanyRelationService companyRelationService;
	@Autowired
	private PremisesRelationService premisesRelationService;
	@Autowired
	private CompanyService companyService;
	@Autowired
	private PremisesService premisesService;
	@Autowired
	private PartnerInfoService partnerInfoService;
	@Autowired
	private UploadExcelService uploadExcelService;
	@Autowired
	private ImportErrorService importErrorService;
	@Autowired
	private DepartmentMapper mapper;
	@Autowired
	private PartnerInfoMapper partnerInfoMapper;
	@Autowired
	private DataPermissionService dataPermissionService;
	@Autowired
	DeptPermissionService deptPermissionService;
	@Autowired
	ModelInfoService modelInfoService;
	
	@Override
	public AddDeptResDto create(AddDeptReqDto addDeptReqDto) {
		AddDeptResDto res = new AddDeptResDto();
		if (StringUtils.isBlank(addDeptReqDto.getUserId())) {
			throw new TServerException("用户id为空");
		}
		if (StringUtils.isBlank(addDeptReqDto.getParentId())) {
			throw new TServerException("parentId为空");
		}
		if (StringUtils.isBlank(addDeptReqDto.getDepartmentName())) {
			throw new TServerException("部门名称为空");
		}
		Department dept = departmentDao.selectById(Long.parseLong(addDeptReqDto.getParentId()));
		DepartmentDto dto = new DepartmentDto();
		dto.setParentId(Long.valueOf(addDeptReqDto.getParentId()));
		dto.setDepartmentCode(addDeptReqDto.getDepartmentCode());
		dto.setDepartmentName(addDeptReqDto.getDepartmentName());
		dto.setRemark(addDeptReqDto.getRemark());
		dto.setCreateUserId(Long.parseLong(addDeptReqDto.getUserId()));
		dto.setMerchantId(dept.getMerchantId());
		if(Objects.nonNull(dept.getLayer())){
			dto.setLayer(dept.getLayer() + 1);
		}
		dto.setParentId(Long.parseLong(addDeptReqDto.getParentId()));
		dto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		departmentDao.create(dto);

		deptPermissionService.initDeptPermissionCode(dept.getMerchantId());

		res.setResult(ResultEnum.SUCCESS.getNo());
		res.setResultMsg("操作成功");
		return res;
	}
	
	@Override
	public EditDeptResDto update(EditDeptReqDto editDeptReqDto) {
		EditDeptResDto res = new EditDeptResDto();
		if (StringUtils.isBlank(editDeptReqDto.getId())) {
			throw new TServerException("部门id为空");
		}
		if (StringUtils.isBlank(editDeptReqDto.getDepartmentName())) {
			throw new TServerException("部门名称为空");
		}
		DepartmentDto dto = new DepartmentDto();
		dto.setDepartmentCode(editDeptReqDto.getDepartmentCode());
		dto.setDepartmentName(editDeptReqDto.getDepartmentName());
		dto.setRemark(editDeptReqDto.getRemark());
		dto.setId(Long.parseLong(editDeptReqDto.getId()));
		departmentDao.update(dto);
		res.setResult(ResultEnum.SUCCESS.getNo());
		res.setResultMsg("操作成功");
		return res;
	}
	
	@Override
	@Transactional(isolation = Isolation.READ_COMMITTED)
	public DelDeptResDto delOrg(DelDeptReqDto delDeptReqDto) {
		DelDeptResDto res = new DelDeptResDto();
		res.setResult(ResultEnum.FAIL.getNo());
		// 当前登录用户
		boolean hasPartnerFlag = departmentDao.hasPartner(false, Long.parseLong(delDeptReqDto.getId()));
		if (hasPartnerFlag) {
			res.setResultMsg("部门或子部门下存在启用员工,不能删除!");
			return res;
		} else {
			DepartmentDto departmentDto = new DepartmentDto();
			departmentDto.setId(Long.parseLong(delDeptReqDto.getId()));
			departmentDto.setOptUser(Long.parseLong(delDeptReqDto.getUserId()));
			// 删除第一层级，记录操作日志
			departmentDao.destroy(departmentDto);
			// 删除该层级下的子节点
			departmentDao.delDept(departmentDto.getId());
		}
		res.setResult(ResultEnum.SUCCESS.getNo());
		res.setResultMsg("操作成功");
		return res;
	}
	
	@Override
	public GetDeptTreeResDto getDeptTree(GetDeptTreeReqDto deptTreeReqDto) {
		if (deptTreeReqDto.getMerchantId() == null) {
			throw new TServerException("商户id为空");
		}
		GetDeptTreeResDto res = new GetDeptTreeResDto();
		// 获取公司下的部门信息
		DepartmentDto departmentDto = new DepartmentDto();
		departmentDto.setMerchantId(deptTreeReqDto.getMerchantId());
		List<Department> deptList = departmentDao.selectListByDto(departmentDto);
		// 组装Znodes
		List<ZNodes> nodesList = new ArrayList<ZNodes>();
		for (Department dt : deptList) {
			ZNodes zNode = new ZNodes();
			zNode.setId(String.valueOf(dt.getId()));
			zNode.setMerchantId(dt.getMerchantId());
			if (dt.getParentId() == 0 || dt.getParentId() == -1) {
				zNode.setpId(String.valueOf(departmentDto.getMerchantId()));
			} else {
				zNode.setpId(String.valueOf(dt.getParentId()));
			}
			zNode.setName(dt.getDepartmentName());
			zNode.setOther(dt.getRemark());
			nodesList.add(zNode);
		}
		res.setResult(ResultEnum.SUCCESS.getNo());
		res.setNodesList(nodesList);
		return res;
	}

	@Override
	public GetDeptTreeResDto getChangeDeptTree(GetDeptTreeReqDto deptTreeReqDto) {
		if (deptTreeReqDto.getMerchantId() == null) {
			throw new TServerException("商户id为空");
		}
		GetDeptTreeResDto res = new GetDeptTreeResDto();
		// 获取公司下的部门信息
		DepartmentDto departmentDto = new DepartmentDto();
		departmentDto.setMerchantId(deptTreeReqDto.getMerchantId());
		List<Department> deptList = departmentDao.selectPartListByDto(departmentDto);
		// 组装Znodes
		List<ZNodes> nodesList = new ArrayList<ZNodes>();
		for (Department dt : deptList) {
			ZNodes zNode = new ZNodes();
			zNode.setId(String.valueOf(dt.getId()));
			zNode.setMerchantId(dt.getMerchantId());
			if (dt.getParentId() == 0 || dt.getParentId() == -1) {
				zNode.setpId(String.valueOf(departmentDto.getMerchantId()));
			} else {
				zNode.setpId(String.valueOf(dt.getParentId()));
			}
			zNode.setName(dt.getDepartmentName());
			zNode.setOther(dt.getRemark());
			nodesList.add(zNode);
		}
		res.setResult(ResultEnum.SUCCESS.getNo());
		res.setNodesList(nodesList);
		return res;
	}

	@Override
	public GetAgentOrgByDevOrgResDto getAgentOrgByDevOrg(GetAgentOrgByDevOrgReqDto reqDto) {
		GetAgentOrgByDevOrgResDto res = new GetAgentOrgByDevOrgResDto();
		CompanyRelationDto crDto = new CompanyRelationDto();
		crDto.setDevCompany(reqDto.getDevCompanyId());
		crDto.setRelationStatus(RelationStatusEnum.VALID.getNo());
		crDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        List<CompanyRelationDto> crDtoList = companyRelationService.selectDtoListByDto(crDto);
		res.setAgentOrgList(crDtoList);
		res.setResult(ResultEnum.SUCCESS.getNo());
		return res;
	}
	
	@Override
	public GetAgentOrgByPremisesResDto getAgentOrgByPremises(GetAgentOrgByPremisesReqDto getAgentOrgByPremisesReqDto) {
		if (getAgentOrgByPremisesReqDto.getDevCompanyId() == null) {
			throw new TServerException("开发商id为空");
		}
		if (getAgentOrgByPremisesReqDto.getPremisesId() == null) {
			throw new TServerException("楼盘id为空");
		}
		CompanyRelationDto companyRelationDto = new CompanyRelationDto();
		companyRelationDto.setDevCompany(getAgentOrgByPremisesReqDto.getDevCompanyId());
		List<CompanyRelationDto> crDtoList = companyRelationService.selectDtoListByDto(companyRelationDto);

		PremisesRelationDto entity = new PremisesRelationDto();
		entity.setDevCompanyId(getAgentOrgByPremisesReqDto.getDevCompanyId());
		entity.setPremisesId(getAgentOrgByPremisesReqDto.getPremisesId());
		entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
		entity.setOrders("create_time desc");
		List<PremisesRelation> prList = premisesRelationService.selectListByDto(entity);

		GetAgentOrgByPremisesResDto res = new GetAgentOrgByPremisesResDto();
		List<PremisesRelationDto> agentOrgList = new ArrayList<>();
		for(CompanyRelationDto crDto: crDtoList){
			PremisesRelationDto prDto = new PremisesRelationDto();
			prDto.setAgentCompanyId(crDto.getAgentCompany());
			prDto.setAgentCompanyName(crDto.getAgentCompanyName());
			prDto.setStatus(RelationStatusEnum.INVALID.getNo());
			for (PremisesRelation pr: prList){
				if(crDto.getAgentCompany().equals(pr.getAgentCompanyId())){
					prDto.setStatus(pr.getStatus());
					break;
				}
			}
			agentOrgList.add(prDto);
		}
		res.setAgentOrgList(agentOrgList);
		res.setResult(ResultEnum.SUCCESS.getNo());
		return res;
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
	public AddAgentOrgResDto addAgentOrg(AddAgentOrgReqDto addAgentOrgReqDto) {
		AddAgentOrgResDto res = new AddAgentOrgResDto();
		if (StringUtils.isBlank(addAgentOrgReqDto.getLoginType())) {
			throw new TServerException("系统id为空");
		}
		if (SystemIdEnum.DEVELOPERS.getCode().equals(addAgentOrgReqDto.getLoginType())) {
			// 开发商控台新增合作机构
			saveOrgFromDevelopers(addAgentOrgReqDto);
		}
		if (SystemIdEnum.AGENCY_h5.getCode().equals(addAgentOrgReqDto.getLoginType()) ||SystemIdEnum.WEAPP_AGENCY.getCode().equals(addAgentOrgReqDto.getLoginType()) || SystemIdEnum.APP_AGENCY.getCode().equals(addAgentOrgReqDto.getLoginType())) {
			// 分销h5新增合作机构
			saveOrgFromAgencyH5(addAgentOrgReqDto);
		}
		res.setResult(ResultEnum.SUCCESS.getNo());
		res.setResultMsg("操作成功");
		return res;
	}
	
	// 开发商后台新增机构
	public void saveOrgFromDevelopers(AddAgentOrgReqDto addAgentOrgReqDto) {
		if (StringUtils.isBlank(addAgentOrgReqDto.getCompanyName())) {
			throw new TServerException("公司名称为空");
		}
		if (StringUtils.isBlank(addAgentOrgReqDto.getProvince())) {
			throw new TServerException("省份为空");
		}
		if (StringUtils.isBlank(addAgentOrgReqDto.getAddress())) {
			throw new TServerException("地址为空");
		}
		if (StringUtils.isBlank(addAgentOrgReqDto.getUserId())) {
			throw new TServerException("用户id为空");
		}
		if (addAgentOrgReqDto != null && StringUtils.isNotBlank(addAgentOrgReqDto.getParentId())) {
			// 新增第二级及以下合作机构，不需要绑定其它关系
			Department dept = departmentDao.selectById(Long.parseLong(addAgentOrgReqDto.getParentId()));
			;
			DepartmentDto departmentDto = new DepartmentDto();
			departmentDto.setDepartmentName(addAgentOrgReqDto.getCompanyName());
			departmentDto.setMerchantId(dept.getMerchantId());
			departmentDto.setCreateUserId(Long.parseLong(addAgentOrgReqDto.getUserId()));
			departmentDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			departmentDto.setParentId(Long.parseLong(addAgentOrgReqDto.getParentId()));
			departmentDto.setOptUser(Long.parseLong(addAgentOrgReqDto.getUserId()));
			if (StringUtils.isNotBlank(addAgentOrgReqDto.getParentId())) {
				departmentDto.setPrincipal(Long.parseLong(addAgentOrgReqDto.getParentId()));
			}
			departmentDao.create(departmentDto);
		} else {
			// 新增第一级机构
			// 查询其开发商的是否默认佣金设置
			CompanyDto entity = new CompanyDto();
			Company com = companyService.selectById(addAgentOrgReqDto.getHigherId());
			entity.setCommissionFlag(com.getCommissionFlag());
			if (StringUtils.isNotBlank(addAgentOrgReqDto.getPrincipal())) {
				entity.setPrincipal(Long.parseLong(addAgentOrgReqDto.getPrincipal()));
			}
			entity.setCompanyName(addAgentOrgReqDto.getCompanyName());
			// 当新增第一级机构时，判断机构名称是否存在
			boolean fg = isExsitsCoo(entity, addAgentOrgReqDto.getHigherId());
			if (fg) {
				throw new TServerException("分销商名称已存在，请核实后重新输入");
			}
			entity.setExternalNumber("");
			entity.setCompanyType(1L);
			entity.setOptUser(Long.parseLong(addAgentOrgReqDto.getUserId()));
			entity.setStatus(CheckStatusEnum.SUCCESS.getNo());
			entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
			entity.setAdress(addAgentOrgReqDto.getAddress());
			entity.setProvince(Long.parseLong(addAgentOrgReqDto.getProvince()));
			if (StringUtils.isNotBlank(addAgentOrgReqDto.getCity())) {
				entity.setCity(Long.parseLong(addAgentOrgReqDto.getCity()));
			}
			entity.setOptUser(Long.parseLong(addAgentOrgReqDto.getUserId()));
			companyService.saveOrUpdate(entity);
			// 向渠道关系表中插入数据
			CompanyRelationDto companyRelationDto = new CompanyRelationDto();
			companyRelationDto.setCreateUserId(Long.parseLong(addAgentOrgReqDto.getUserId()));
			companyRelationDto.setDevCompany(addAgentOrgReqDto.getHigherId());
			companyRelationDto.setAgentCompany(entity.getId());
			companyRelationDto.setRelationStatus(RelationStatusEnum.VALID.getNo());
			companyRelationDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			companyRelationService.create(companyRelationDto);
			// 新增一级机构时，向楼盘关系表中绑定默认全部楼盘
			insertPremisesRelation(addAgentOrgReqDto.getHigherId(), entity.getId());
			Company company = companyService.selectById(entity.getId());
			entity.setStatus(company.getStatus());
			entity.setCity(company.getCity());
			entity.setMerchantCode(company.getMerchantCode());
			entity.setDomain(company.getDomain());
			// 更新新增机构的公司代码
			updateCompanyCode(entity);
		}
	}
	
	// 新增第一层级合作机构时，判断是否存在
	private boolean isExsitsCoo(CompanyDto entity, Long devCompanyId) {
		if (entity.getId() != null) {
			// 当用户编辑时
			Company company = companyService.selectById(entity.getId());
			if (company.getCompanyName().equals(entity.getCompanyName())) {
				// 当用户编辑时未改变公司名时，不做验证
				return false;
			}
		}
		CompanyRelationDto dto = new CompanyRelationDto();
		dto.setDevCompany(devCompanyId);
		dto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		List<CompanyRelation> lists = companyRelationService.selectListByDto(dto);
		List<Long> list = new ArrayList<Long>();
		for (CompanyRelation relation : lists) {
			list.add(relation.getAgentCompany());
		}
		if (list.size() > 0) {
			CompanyDto cDto = new CompanyDto();
			cDto.setIds(list);
			// 审核失败的公司不进行查重判断
			cDto.setStatusList(Arrays.asList(CheckStatusEnum.TODO.getNo(), CheckStatusEnum.SUCCESS.getNo(),
					CheckStatusEnum.NOT_REQUIRED.getNo()));
			List<CompanyDto> companys = companyService.selectListByIds(cDto);
			for (CompanyDto company : companys) {
				if (entity.getCompanyName().equals(company.getCompanyName())) {
					return true;
				}
			}
		}
		return false;
	}
	
	private void insertPremisesRelation(Long devCompanyId, Long agentCompanyId) {
		// 查询该开发商下的所有楼盘
		PremisesDto pDto = new PremisesDto();
		pDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		pDto.setCompanyId(devCompanyId);
		List<Premises> lists = premisesService.selectListByDto(pDto);
		for (Premises premises : lists) {
			// 在楼盘合作关系表中绑定合作机构和楼盘信息
			PremisesRelationDto relationDto = new PremisesRelationDto();
			relationDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			relationDto.setDevCompanyId(devCompanyId);
			relationDto.setAgentCompanyId(agentCompanyId);
			relationDto.setPremisesId(premises.getId());
			relationDto.setStatus(MechanismStatusEnum.enable.getNo());
			premisesRelationService.create(relationDto);
		}
	}
	
	private String updateCompanyCode(CompanyDto entity) {
		try {
			Company company = new Company();
			BeanUtils.copyProperties(entity, company);
			String companyCode = companyService.getCompanyCode(company);
			CompanyDto dto = new CompanyDto();
			dto.setId(company.getId());
			dto.setCompanyCode(companyCode);
			companyService.updateByMyid(dto);
			return companyCode;
		} catch (Exception e) {
			log.error("OrganizationServiceImpl, company: {} error: {}", entity, e);
		}
		return null;
	}
	
	// 分销h5注册公司
	public void saveOrgFromAgencyH5(AddAgentOrgReqDto addAgentOrgReqDto) {
		if (StringUtils.isBlank(addAgentOrgReqDto.getCompanyName())) {
			throw new TServerException("公司全称为空");
		}
		if (StringUtils.isBlank(addAgentOrgReqDto.getProvince())) {
			throw new TServerException("所在省份未选择");
		}
		if (StringUtils.isBlank(addAgentOrgReqDto.getCity())) {
			throw new TServerException("所在城市未选择");
		}
		if (StringUtils.isBlank(addAgentOrgReqDto.getAddress())) {
			throw new TServerException("详细地址为空");
		}
		if (StringUtils.isBlank(addAgentOrgReqDto.getChargeMan())) {
			throw new TServerException("负责人姓名为空");
		}
		if (StringUtils.isBlank(addAgentOrgReqDto.getPhone())) {
			throw new TServerException("手机号码为空");
		}
		if (StringUtils.isBlank(addAgentOrgReqDto.getUserId())) {
			throw new TServerException("用户id为空");
		}
		if (!RegexUtil.isMobileSimple(addAgentOrgReqDto.getPhone())) {
			throw new TServerException("手机号码格式错误");
		}
		if (StringUtils.isBlank(addAgentOrgReqDto.getDomain()) && StringUtils.isBlank(addAgentOrgReqDto.getCompanyUuid())) {
			throw new TServerException("公司信息获取失败");
		}
		PartnerInfoDto queryPartnerInfo = new PartnerInfoDto();
		String domainUrl = addAgentOrgReqDto.getDomain();
		CompanyDto cDto = new CompanyDto();
		cDto.setDomain(domainUrl);
		cDto.setCompanyUuid(addAgentOrgReqDto.getCompanyUuid());
		cDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		cDto.setStatus(CheckStatusEnum.SUCCESS.getNo());
		List<Company> lists = companyService.selectListByDto(cDto);
		if (lists.size() > 0) {
			CompanyRelationDto relationDto = new CompanyRelationDto();
			relationDto.setDevCompany(lists.get(0).getId());
			
			// 公司名称查重（同一域名下---》同一开发商）
			Company newCompany = new Company();
			newCompany.setCompanyName(addAgentOrgReqDto.getCompanyName());
			boolean isExist = isExsitsCoo(newCompany, lists.get(0).getId());
			if (isExist) {
				throw new TServerException("公司名称已存在");
			}
			List<CompanyRelation> relationList = companyRelationService.selectListByDto(relationDto);
			List<Long> companyIds = new ArrayList<Long>();
			for (CompanyRelation relation : relationList) {
				companyIds.add(relation.getAgentCompany());
			}
			// 设置开发商的id
			companyIds.add(lists.get(0).getId());
			if (companyIds.size() > 0) {
				queryPartnerInfo.setCompanyIds(companyIds);
			} else {
				throw new TServerException("通过域名未找到合作的分销商！");
			}
		} else {
			throw new TServerException("通过域名未找到渠道商");
		}
		PartnerInfo partnerInfo = partnerInfoService.selectById(Long.parseLong(addAgentOrgReqDto.getUserId()));
		if (null == partnerInfo) {
			throw new TServerException("用户信息获取失败");
		}
		queryPartnerInfo.setPhone(addAgentOrgReqDto.getPhone());
		if (!addAgentOrgReqDto.getPhone().equals(partnerInfo.getPhone())) {
			// 当负责人和登录人的手机号不一致时才去校验
			List<PartnerInfo> partnerList = partnerInfoService.checkRepeat(queryPartnerInfo);
			if (null == partnerList || partnerList.size() > 0) {
				throw new TServerException("该手机号码已存在，请核实！");
			}
		}
		CompanyDto companyDto = new CompanyDto();
		companyDto.setCompanyName(addAgentOrgReqDto.getCompanyName());
		companyDto.setProvince(Long.parseLong(addAgentOrgReqDto.getProvince()));
		companyDto.setCity(Long.parseLong(addAgentOrgReqDto.getCity()));
		companyDto.setAdress(addAgentOrgReqDto.getAddress());
		companyDto.setChargeMan(addAgentOrgReqDto.getChargeMan());
		companyDto.setPhone(addAgentOrgReqDto.getPhone());
		companyDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		companyDto.setStatus(CheckStatusEnum.TODO.getNo());
		companyDto.setCreateUserId(partnerInfo.getId());
		companyDto.setExternalNumber("");
		companyDto.setCompanyType(Long.parseLong("1"));
		companyDto.setCommissionFlag("1");
		CompanyDto entity = companyService.create(companyDto);
		// 更新个人信息中的公司id
		PartnerInfoDto pDto = new PartnerInfoDto();
		pDto.setId(partnerInfo.getId());
		pDto.setHigherid(entity.getId());
		partnerInfoService.update(pDto);
		// 在部门表中绑定顶级机构
		DepartmentDto departmentDto = new DepartmentDto();
		departmentDto.setDepartmentCode(String.valueOf(entity.getId()));
		departmentDto.setParentId(0L);
		departmentDto.setDepartmentName(entity.getCompanyName());
		departmentDto.setMerchantId(entity.getId());
		departmentDto.setCreateUserId(0L);
		departmentDto.setDelFlag(DelFlagEnum.DEL.getNo());
		departmentDto.setUpdateTime(Calendar.getInstance().getTime());
		departmentDto.setReward(entity.getReward());
		departmentDto.setPremisesCommission(entity.getPremisesCommission());
		departmentDto.setCommission(entity.getCommission());
		departmentDto.setCommissionWay(entity.getCommissionWay());
		departmentDto.setPrincipal(entity.getPrincipal());
		departmentDto.setOptUser(partnerInfo.getId());
		departmentDao.create(departmentDto);
		// 向渠道关系表中插入数据
		CompanyRelationDto companyRelationDto = new CompanyRelationDto();
		companyRelationDto.setCreateUserId(partnerInfo.getId());
		companyRelationDto.setCreateTime(Calendar.getInstance().getTime());
		companyRelationDto.setDevCompany(lists.get(0).getId());
		companyRelationDto.setAgentCompany(entity.getId());
		companyRelationDto.setRelationStatus(RelationStatusEnum.VALID.getNo());
		companyRelationDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		companyRelationService.create(companyRelationDto);
	}
	
	private boolean isExsitsCoo(Company agentCompany, Long devCompanyId) {
		if (agentCompany.getId() != null) {
			Company oldAgentCompany = companyService.selectById(agentCompany.getId());
			if (agentCompany.getCompanyName().equals(oldAgentCompany.getCompanyName())) {
				return false;
			}
		}
		
		CompanyRelationDto dto = new CompanyRelationDto();
		dto.setDevCompany(devCompanyId);
		dto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		List<CompanyRelation> lists = companyRelationService.selectListByDto(dto);
		List<Long> list = new ArrayList<Long>();
		for (CompanyRelation relation : lists) {
			list.add(relation.getAgentCompany());
		}
		if (list.size() > 0) {
			CompanyDto cDto = new CompanyDto();
			cDto.setIds(list);
			List<CompanyDto> companys = companyService.selectListByIds(cDto);
			for (CompanyDto company : companys) {
				if (agentCompany.getCompanyName().equals(company.getCompanyName())) {
					return true;
				}
			}
		}
		return false;
	}
	
	@Override
	@Transactional(isolation = Isolation.READ_COMMITTED)
	public UpdateAgentOrgResDto updateAgentOrg(UpdateAgentOrgReqDto updateAgentOrgReqDto) {
		UpdateAgentOrgResDto res = new UpdateAgentOrgResDto();
		if (StringUtils.isBlank(updateAgentOrgReqDto.getLoginType())) {
			throw new TServerException("系统id为空");
		}
		if (SystemIdEnum.DEVELOPERS.getCode().equals(updateAgentOrgReqDto.getLoginType())) {
			// 开发商控台编辑合作机构
			updateOrgFromDevelopers(updateAgentOrgReqDto);
		}
		if (SystemIdEnum.AGENCY_h5.getCode().equals(updateAgentOrgReqDto.getLoginType()) ||SystemIdEnum.WEAPP_AGENCY.getCode().equals(updateAgentOrgReqDto.getLoginType()) || SystemIdEnum.APP_AGENCY.getCode().equals(updateAgentOrgReqDto.getLoginType())) {
			// 分销h5编辑合作机构
			updateOrgFromAgencyH5(updateAgentOrgReqDto);
		}
		res.setResult(ResultEnum.SUCCESS.getNo());
		res.setResultMsg("操作成功");
		return res;
	}
	
	public void updateOrgFromDevelopers(UpdateAgentOrgReqDto reqDto) {
		if (reqDto.getCompanyId() == null) {
			throw new TServerException("id为空");
		}
		if (StringUtils.isBlank(reqDto.getCompanyName())) {
			throw new TServerException("公司名称为空");
		}
		if (StringUtils.isBlank(reqDto.getProvince())) {
			throw new TServerException("省份为空");
		}
		if (StringUtils.isBlank(reqDto.getAddress())) {
			throw new TServerException("地址为空");
		}
		if (StringUtils.isBlank(reqDto.getUserId())) {
			throw new TServerException("用户id为空");
		}
		CompanyDto entity = new CompanyDto();
		entity.setExternalNumber("");
		if (reqDto.getCompanyId() != null) {
			// 编辑合作机构时，由于其创建人，负责人这些可以为空编辑，所以会把注册申请的公司信息去掉，这里查询一遍
			Company comp = companyService.selectById(reqDto.getCompanyId());
			if (comp.getCreateUserId() != null) {
				entity.setCreateUserId(comp.getCreateUserId());
			}
			if (StringUtils.isNotBlank(comp.getPhone())) {
				entity.setPhone(comp.getPhone());
			}
			if (StringUtils.isNotBlank(comp.getChargeMan())) {
				entity.setChargeMan(comp.getChargeMan());
			}
			if (StringUtils.isNotBlank(comp.getStatus())) {
				entity.setStatus(comp.getStatus());
			}
			if (StringUtils.isNotBlank(comp.getMerchantCode())) {
				entity.setMerchantCode(comp.getMerchantCode());
			}
			if (StringUtils.isNotBlank(comp.getDomain())) {
				entity.setDomain(comp.getDomain());
			}
			companyService.saveOrUpdate(entity);
		}
	}
	
	public void updateOrgFromAgencyH5(UpdateAgentOrgReqDto updateAgentOrgReqDto) {
		if (updateAgentOrgReqDto.getCompanyId() == null) {
			throw new TServerException("公司id为空");
		}
		if (StringUtils.isBlank(updateAgentOrgReqDto.getCompanyName())) {
			throw new TServerException("公司全称为空");
		}
		if (StringUtils.isBlank(updateAgentOrgReqDto.getProvince())) {
			throw new TServerException("所在省份未选择");
		}
		if (StringUtils.isBlank(updateAgentOrgReqDto.getCity())) {
			throw new TServerException("所在城市未选择");
		}
		if (StringUtils.isBlank(updateAgentOrgReqDto.getAddress())) {
			throw new TServerException("详细地址为空");
		}
		if (StringUtils.isBlank(updateAgentOrgReqDto.getChargeMan())) {
			throw new TServerException("负责人姓名为空");
		}
		if (StringUtils.isBlank(updateAgentOrgReqDto.getPhone())) {
			throw new TServerException("手机号码为空");
		}
		if (!RegexUtil.isMobileSimple(updateAgentOrgReqDto.getPhone())) {
			throw new TServerException("手机号码格式错误");
		}
		Company company = companyService.selectById(updateAgentOrgReqDto.getCompanyId());
		if (CheckStatusEnum.SUCCESS.getNo().equals(company.getStatus())) {
			throw new TServerException("公司已审核通过，不能再次编辑");
		}
		
		if (StringUtils.isBlank(updateAgentOrgReqDto.getDomain()) && StringUtils.isBlank(updateAgentOrgReqDto.getCompanyUuid())) {
			throw new TServerException("公司信息获取失败");
		}
		// 设置编辑公司的信息
		CompanyDto companyDto = new CompanyDto();
		companyDto.setId(updateAgentOrgReqDto.getCompanyId());
		companyDto.setCompanyName(updateAgentOrgReqDto.getCompanyName());
		companyDto.setProvince(Long.parseLong(updateAgentOrgReqDto.getProvince()));
		companyDto.setCity(Long.parseLong(updateAgentOrgReqDto.getCity()));
		companyDto.setAdress(updateAgentOrgReqDto.getAddress());
		companyDto.setChargeMan(updateAgentOrgReqDto.getChargeMan());
		companyDto.setPhone(updateAgentOrgReqDto.getPhone());
		
		PartnerInfoDto queryPartnerInfo = new PartnerInfoDto();
		String domainUrl = updateAgentOrgReqDto.getDomain();
		CompanyDto cDto = new CompanyDto();
		cDto.setDomain(domainUrl);
		cDto.setCompanyUuid(updateAgentOrgReqDto.getCompanyUuid());
		cDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		cDto.setStatus(CheckStatusEnum.SUCCESS.getNo());
		List<Company> lists = companyService.selectListByDto(cDto);
		if (lists.size() > 0) {
			CompanyRelationDto relationDto = new CompanyRelationDto();
			relationDto.setDevCompany(lists.get(0).getId());
			// 公司名称查重 （同一域名下 --》同一个开发商）
			boolean isCompanyExist = isExsitsCoo(companyDto, lists.get(0).getId());
			if (isCompanyExist) {
				throw new TServerException("公司名称已存在");
			}
			List<CompanyRelation> relationList = companyRelationService.selectListByDto(relationDto);
			List<Long> companyIds = new ArrayList<Long>();
			for (CompanyRelation relation : relationList) {
				companyIds.add(relation.getAgentCompany());
			}
			if (companyIds.size() > 0) {
				queryPartnerInfo.setCompanyIds(companyIds);
			} else {
				throw new TServerException("通过域名未找到合作的分销商！");
			}
		} else {
			throw new TServerException("通过域名未找到渠道商");
		}
		PartnerInfo partnerInfo = partnerInfoService.selectById(Long.valueOf(updateAgentOrgReqDto.getUserId()));
		if (null == partnerInfo) {
			throw new TServerException("用户信息获取失败");
		}
		queryPartnerInfo.setPhone(companyDto.getPhone());
		if (!partnerInfo.getPhone().equals(companyDto.getPhone())) {
			// 登录人和负责人的手机号不一致时再校验
			List<PartnerInfo> partnerList = partnerInfoService.checkRepeat(queryPartnerInfo);
			if (null == partnerList || partnerList.size() > 0) {
				throw new TServerException("该手机号码已存在，请核实！");
			}
		}
		companyDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		companyDto.setStatus(CheckStatusEnum.TODO.getNo());
		companyDto.setCreateUserId(partnerInfo.getId());
		companyDto.setExternalNumber("");
		companyDto.setCompanyType(Long.parseLong("1"));
		companyDto.setCommissionFlag("1");
		int i = companyService.update(companyDto);
		if (i == 1) {
			DepartmentDto departmentDto = new DepartmentDto();
			departmentDto.setDepartmentName(companyDto.getCompanyName());
			departmentDto.setMerchantId(companyDto.getId());
			departmentDto.setParentId(0l);// 只修改根节点
			// 李晓进：审核未通过的 del_flag =1
			departmentDto.setDelFlag(DelFlagEnum.DEL.getNo());
			departmentDao.updateByMerchantId(departmentDto);
		}
	}
	
	@Override
	public GetAgentOrgTreeResDto getAgentOrgTree(GetAgentOrgTreeReqDto getAgentOrgTreeReqDto) {
		GetAgentOrgTreeResDto resDto = new GetAgentOrgTreeResDto();
		resDto.setResult(ResultEnum.FAIL.getNo());
		if (StringUtils.isBlank(getAgentOrgTreeReqDto.getUserId())) {
			resDto.setResultMsg("请求超时,请重试!");
			return resDto;
		}
		PartnerInfo pi = partnerInfoService.selectById(Long.parseLong(getAgentOrgTreeReqDto.getUserId()));
		if (null == pi) {
			resDto.setResultMsg("请求超时,请重试!");
			return resDto;
		}
		
		List<ZNodes> nodesList = new ArrayList<>();
		//获取公司下的合作机构
		CompanyRelationDto crDto = new CompanyRelationDto();
		crDto.setDevCompany(pi.getHigherid());
		crDto.setRelationStatus(RelationStatusEnum.VALID.getNo());
		crDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		crDto.setAgentCompany(getAgentOrgTreeReqDto.getpId());
		List<CompanyRelation> crList = companyRelationService.selectListByDto(crDto);
		StringBuilder sb = new StringBuilder();
		if (null != crList && crList.size() > 0) {
			List<Long> companyIds = crList.stream().map(CompanyRelation::getAgentCompany)
					.collect(Collectors.toList());
			CompanyDto companyDto = new CompanyDto();
			companyDto.setIds(companyIds);
			companyDto.setStatus(CheckStatusEnum.SUCCESS.getNo());
			List<CompanyDto> companyDtoList = companyService.selectListByIds(companyDto);
			for (CompanyDto dto : companyDtoList) {
				sb.append(dto.getId() + ",");
			}
		}
		//所有的合作机构Id
		String agentCompanyIds = sb.toString();
		if (StringUtils.isNotBlank(agentCompanyIds)) {
			agentCompanyIds = agentCompanyIds.substring(0, agentCompanyIds.length() - 1);
		}
		if (StringUtils.isEmpty(agentCompanyIds)) {
			resDto.setResult(ResultEnum.SUCCESS.getNo());
			resDto.setNodesList(nodesList);
			return resDto;
		}

		String merchantId = getAgentOrgTreeReqDto.getMerchantId();
		DepartmentDto departmentDto = new DepartmentDto();
		if (merchantId != null && merchantId.length() > 0) {
			departmentDto.setMerchantId(Long.valueOf(merchantId));
		} else {
			departmentDto.setMerchantIds(agentCompanyIds);
		}
		departmentDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		departmentDto.setDepartmentName(getAgentOrgTreeReqDto.getSearchMsg());
		departmentDto.setPrincipalName(getAgentOrgTreeReqDto.getSearchMsg());
		departmentDto.setOrders("create_time desc");
		
		List<DepartmentDto> deptList = new ArrayList<DepartmentDto>();
		// 非管理员根据合作机构只获取对接的部门
		if (!PartnerInfoEnum.ACCOUNT_MECHANISM.getCode().equals(pi.getAccountType())) {
			deptList = getDepartment(agentCompanyIds, pi.getId(), getAgentOrgTreeReqDto.getSearchMsg());
			nodesList = getDepartmentNodes(deptList);
			resDto.setNodesList(nodesList);
			resDto.setResult(ResultEnum.SUCCESS.getNo());
			return resDto;
		} else {
			deptList = departmentDao.selectList(departmentDto);
		}
		
		
		for (DepartmentDto dt : deptList) {
			ZNodes departmentNodes = new ZNodes();
			departmentNodes.setId(String.valueOf(dt.getId()));
			departmentNodes.setMerchantId(dt.getMerchantId());
			if (dt.getParentId() == 0 || dt.getParentId() == -1) {
				departmentNodes.setpId(String.valueOf(departmentDto.getMerchantId()));
			} else {
				departmentNodes.setpId(String.valueOf(dt.getParentId()));
			}
			departmentNodes.setName(dt.getDepartmentName());
			departmentNodes.setOther(dt.getPrincipalName());
			nodesList.add(departmentNodes);
		}
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		resDto.setNodesList(nodesList);
		return resDto;
	}

	@Override
	public GetOrgAssistantListResDto getOrgAssistantList(GetOrgAssistantListReqDto getOrgAssistantListReqDto){
		GetOrgAssistantListResDto resDto = new GetOrgAssistantListResDto();
		Page<DepartmentDto> page = new Page<>();
		DepartmentDto departmentDto = new DepartmentDto();
		//获取登录用户信息
		PartnerInfo partnerInfo = partnerInfoMapper.selectById(Long.parseLong(getOrgAssistantListReqDto.getUserId()));
		if("1".equals(partnerInfo.getAccountType())){
			//非管理员传入对接人
			departmentDto.setPrincipal(Long.parseLong(getOrgAssistantListReqDto.getUserId()));
		}
		departmentDto.setMerchantId(partnerInfo.getHigherid());

		if(StringUtils.isNotBlank(getOrgAssistantListReqDto.getSearchName())){
			departmentDto.setDepartmentName(getOrgAssistantListReqDto.getSearchName());
		}
		//
		int count = mapper.selectOrgAssistantCount(departmentDto);
		page.setTotal(count);

		if(count > 0){
			List<DepartmentDto> list = mapper.selectOrgAssistant(departmentDto,PageUtil.begin(getOrgAssistantListReqDto.getPageNo(),getOrgAssistantListReqDto.getPageSize()),getOrgAssistantListReqDto.getPageSize());
			page.setRows(list);
		}

		resDto.setPage(page);
		resDto.setResult(ResultEnum.SUCCESS.getNo());

		return resDto;
	}

	/**
	 * 2017.9.25新增需求， 对接人只能看自己对接的合作机构 管理员可以看所有的合作机构
	 */
	private List<DepartmentDto> getDepartment(String merchantIds, Long id, String msg) {
		DepartmentDto departmentDto = new DepartmentDto();
		departmentDto.setMerchantIds(merchantIds);
		departmentDto.setPrincipalName(msg);
		departmentDto.setDepartmentName(msg);
		departmentDto.setOrders("create_time desc");
		List<DepartmentDto> deptList = departmentDao.selectList(departmentDto);

		List<DepartmentDto> returnList = new ArrayList<>();

		List<DepartmentDto> managerDeptList = new ArrayList<>();
		Set<DepartmentDto> departmentDtoSet = new HashSet<>();
		// 非管理员 查出对接人是他自己的
		for (DepartmentDto d : deptList) {
			if (id.equals(d.getPrincipal())) {
				// 目前是所有对接人的直属部门
				managerDeptList.add(d);
			}
		}
		departmentDtoSet.addAll(managerDeptList);
		// 查询子部门
		deptList.stream().filter(dto -> StringUtils.isNotEmpty(dto.getPermissionCode())).forEach(dto ->{
			String dtoPermissionCode = dto.getPermissionCode();
			departmentDtoSet.stream().filter(department -> {
				return (department.getPermissionCode() != null &&
				dtoPermissionCode.startsWith(department.getPermissionCode()));
			});
		});
		returnList.addAll(departmentDtoSet);
		return returnList;
	}

	private List<ZNodes> getDepartmentNodes(List<DepartmentDto> deptList) {
		List<ZNodes> list = new ArrayList<>();
		// 组织数据结构
		for (DepartmentDto d : deptList) {
			ZNodes node = new ZNodes();
			node.setId(String.valueOf(d.getId()));
			node.setMerchantId(d.getMerchantId());
			if (d.getParentId() == 0 || d.getParentId() == -1) {
				node.setpId(String.valueOf(d.getMerchantId()));
			} else {
				node.setpId(String.valueOf(d.getParentId()));
			}
			node.setName(d.getDepartmentName());
			node.setOther(d.getPrincipalName());
			list.add(node);
		}
		return list;
	}
	
	@Override
	public GetAgentOrgAuditPageResDto getAgentOrgAuditPage(GetAgentOrgAuditPageReqDto getAgentOrgAuditReqPage) {
		
		GetAgentOrgAuditPageResDto res = new GetAgentOrgAuditPageResDto();
		res.setResult(ResultEnum.FAIL.getNo());
		PartnerInfo partnerInfo = partnerInfoService.selectById(Long.valueOf(getAgentOrgAuditReqPage.getUserId()));
		if (null == partnerInfo) {
			res.setResultMsg("用户获取失败,请刷新页面重试!");
			return res;
		}
		
		String queryCondition = getAgentOrgAuditReqPage.getQueryCondition();
		String state = getAgentOrgAuditReqPage.getState();
		Integer pageNo = getAgentOrgAuditReqPage.getPageNo();
		Integer pageSize = getAgentOrgAuditReqPage.getPageSize();
		CompanyDto entity = new CompanyDto();
		entity.setId(partnerInfo.getHigherid());
		entity.setChargeMan(queryCondition);
		entity.setApplyUserName(queryCondition);
		entity.setPhone(queryCondition);
		entity.setApplyUserPhone(queryCondition);
		entity.setStatus(state);
		Page<CompanyDto> departmentDto = companyService.selectDtoListById(entity, PageUtil.begin(pageNo, pageSize), pageSize);
		departmentDto.setPageInfo(departmentDto.getTotal(), PageUtil.begin(pageNo, pageSize), pageSize * pageNo);
		res.setResult(ResultEnum.SUCCESS.getNo());
		res.setOrgAuditPage(departmentDto);
		return res;
	}
	
	@Override
	public AgentOrgAuditResDto agentOrgAudit(AgentOrgAuditReqDto agentOrgAuditReqDto) {
		AgentOrgAuditResDto res = new AgentOrgAuditResDto();
		PartnerInfo pi = partnerInfoService.selectById(Long.parseLong(agentOrgAuditReqDto.getUserId()));
		CompanyDto entity = new CompanyDto();
		entity.setCreateUserId(agentOrgAuditReqDto.getCreateUserId());
		entity.setStatus(agentOrgAuditReqDto.getStatus());
		entity.setChargeMan(agentOrgAuditReqDto.getChargeMan());
		entity.setPhone(agentOrgAuditReqDto.getPhone());
		entity.setId(agentOrgAuditReqDto.getId());
		entity.setApplyUserPhone(agentOrgAuditReqDto.getApplyUserPhone());
		entity.setDomain(agentOrgAuditReqDto.getDomain());
		entity.setCompanyUuid(agentOrgAuditReqDto.getCompanyUuid());
		companyService.updateStatus(entity, pi);
		res.setResult(ResultEnum.SUCCESS.getNo());
		res.setResultMsg("操作成功");
		return res;
	}
	
	@Override
	public GetAgentOrgByCompanyListResDto getAgentOrgByCompanyPage(GetAgentOrgByCompanyListReqDto reqDto) {
		GetAgentOrgByCompanyListResDto res = new GetAgentOrgByCompanyListResDto();

		CompanyRelationDto crDto = new CompanyRelationDto();
		crDto.setDevCompany(reqDto.getHigherId());
		crDto.setRelationStatus(RelationStatusEnum.VALID.getNo());
		crDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		crDto.setPremisesId(reqDto.getPremisesId());
		crDto.setAgentCompanyName(reqDto.getAgentCompanyName());
		List<CompanyRelationDto> crDtoList =
			companyRelationService.searchDtoListByDto(crDto, PageUtil.begin(reqDto.getPageNo(), reqDto.getPageSize()), reqDto.getPageSize());
		res.setAgentCompanyList(crDtoList);
		res.setResult(ResultEnum.SUCCESS.getNo());
		return res;
	}
	
	@Override
	public GetAgentOrgCountByCompanyResDto getAgentOrgCountByCompany(GetAgentOrgCountByCompanyReqDto reqDto) {

		GetAgentOrgCountByCompanyResDto res = new GetAgentOrgCountByCompanyResDto();
		CompanyRelationDto crDto = new CompanyRelationDto();
		crDto.setDevCompany(reqDto.getHigherId());
		crDto.setRelationStatus(RelationStatusEnum.VALID.getNo());
		crDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		crDto.setAgentCompanyName(reqDto.getAgentCompanyName());
		crDto.setPremisesId(reqDto.getPremisesId());
		Integer count = companyRelationService.searchDtoListByDtoCount(crDto);
		res.setResult(ResultEnum.SUCCESS.getNo());
		res.setCount(count);
		return res;
	}
	
	@Override
	public ImportOrgResDto importOrg(ImportOrgReqDto reqDto)
		throws Exception {
		MultipartFile file = null;
		Iterator<String> fileNames = reqDto.getMulRequest().getFileNames();
		if (StringUtils.isBlank(reqDto.getOptType())) {
			throw new TServerException("操作类型为空");
		}
		if (StringUtils.isBlank(reqDto.getUserId())) {
			throw new TServerException("用户id为空");
		}
		ImportOrgResDto res = new ImportOrgResDto();
		if (fileNames.hasNext()) {
			String fileName = fileNames.next(); // 附件对应的参数名
			if (!isExcel(fileName)) {
				throw new TServerException("请选择正确的excel");
			}
			
			file = reqDto.getMulRequest().getFile(fileName); // 获取到附件
			if (file == null) {
				throw new TServerException("批量导入失败,请刷新页面后重试");
			}
			String optType = reqDto.getOptType();
			Long userId = Long.parseLong(reqDto.getUserId());
			//当前登录用户
			PartnerInfo currLoginUser = partnerInfoService.selectById(userId);
			Long parentId = reqDto.getParentId();
			Map<String, String> map = new HashMap<String, String>();
			if ("1".equals(optType)) {
				// 导入机构
				map = uploadExcelService.uploadExcel(parentId, currLoginUser, file.getInputStream(), fileName);
				// 刷新用户当前机构权限Code
				deptPermissionService.initDeptPermissionCode(currLoginUser.getHigherid());
				res.setResult(map.get("result"));
				res.setResultMsg(map.get("msg"));
				if ("1".equals(map.get("result"))) {
					res.setUuid(map.get("data"));
				}
			} else if ("2".equals(optType)) {
				// 导入员工
				map = uploadExcelService.uploadExcelUser(userId, file.getInputStream(), fileName);
				res.setResult(map.get("result"));
				res.setResultMsg(map.get("msg"));
				if ("1".equals(map.get("result"))) {
					res.setUuid(map.get("data"));
				}
			} else {
				res.setResult(ResultEnum.FAIL.getNo());
				res.setResultMsg("批量导入失败");
			}
		} else {
			// 读取文件失败
			res.setResult(ResultEnum.FAIL.getNo());
			res.setResultMsg("批量导入失败");
		}
		return res;
	}
	
	// 判断上传的附件是否是excel
	public boolean isExcel(String suffix) {
		boolean flag = false;
		String type = "xls|xlsx";
		if (type.indexOf(suffix.toLowerCase()) > 0) {
			flag = true;
		}
		return flag;
	}
	
	@Override
	public GetAgentOrgByCompanyCodeResDto getAgentOrgByCompanyCode(GetAgentOrgByCompanyCodeReqDto reqDto) {
		GetAgentOrgByCompanyCodeResDto res = new GetAgentOrgByCompanyCodeResDto();
		String companyCode = reqDto.getCompanyCode().toUpperCase();
		String domainUrl = reqDto.getDomain();
		
		// 根据域名获取公司信息
		CompanyDto cDto = new CompanyDto();
		cDto.setDomain(domainUrl);
		cDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		cDto.setStatus(CheckStatusEnum.SUCCESS.getNo());
		cDto.setCompanyUuid(reqDto.getCompanyUuid());
		List<Company> lists = companyService.selectListByDto(cDto);
		List<Long> companyIds = new ArrayList<>();
		if (lists.size() > 0) {
			CompanyRelationDto relationDto = new CompanyRelationDto();
			relationDto.setDevCompany(lists.get(0).getId());
			List<CompanyRelation> relationList = companyRelationService.selectListByDto(relationDto);
			for (CompanyRelation relation : relationList) {
				companyIds.add(relation.getAgentCompany());
			}
		} else {
			throw new TServerException("未找到渠道商");
		}
		// 查询是否存在该公司代码的机构
		CompanyDto dto = new CompanyDto();
		if (companyIds.size() == 0) {
			throw new TServerException("未找到合作的分销商！");
		}
		dto.setIds(companyIds);
		dto.setCompanyCode(companyCode);
		dto.setStatus(CheckStatusEnum.SUCCESS.getNo());
		dto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		List<CompanyDto> companyList = companyService.selectListByIds(dto);
		if (companyList.size() > 1) {
			throw new TServerException("数据异常");
		} else if (companyList.size() == 1) {
			res.setCompany(companyList.get(0));
		} else {
			throw new TServerException("未找到匹配公司");
		}
		res.setResult(ResultEnum.SUCCESS.getNo());
		return res;
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public BindCompanyCodeResDto bindCompanyCode(BindCompanyCodeReqDto reqDto) {
		BindCompanyCodeResDto res = new BindCompanyCodeResDto();
		Long userId = Long.parseLong(reqDto.getUserId());
		PartnerInfoDto partnerInfo = new PartnerInfoDto();
		partnerInfo.setId(userId);
		partnerInfo.setDelFlag(DelFlagEnum.UNDEL.getNo());
		PartnerInfo par = partnerInfoService.selectByDto(partnerInfo);
		if(par == null){
			res.setResult(ResultEnum.USER_IS_NULL.getNo());
			res.setResultMsg("未获取用户信息！");
			return res;
		}
		if (par.getUserRoleId() == 0) {
			// 说明申请注册的公司已审核通过
			throw new TServerException("您申请的公司已审核通过，不能再绑定公司,请重新登录");
		}
		
		String companyCode = reqDto.getCompanyCode();
		String domainUrl = reqDto.getDomain();
		CompanyDto cDto = new CompanyDto();
		cDto.setDomain(domainUrl);
		cDto.setCompanyUuid(reqDto.getCompanyUuid());
		cDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		cDto.setStatus(CheckStatusEnum.SUCCESS.getNo());
		List<Company> lists = companyService.selectListByDto(cDto);
		List<Long> companyIds = new ArrayList<>();
		if (lists.size() > 0) {
			CompanyRelationDto relationDto = new CompanyRelationDto();
			relationDto.setDevCompany(lists.get(0).getId());
			List<CompanyRelation> relationList = companyRelationService.selectListByDto(relationDto);
			for (CompanyRelation relation : relationList) {
				companyIds.add(relation.getAgentCompany());
			}
		} else {
			throw new TServerException("通过域名未找到渠道商");
		}
		CompanyDto dto = new CompanyDto();
		if (companyIds.size() == 0) {
			throw new TServerException("通过域名未找到合作的分销商！");
		}
		dto.setIds(companyIds);
		dto.setCompanyCode(companyCode);
		List<CompanyDto> companyList = companyService.selectListByIds(dto);
		if (companyList.size() > 1) {
			throw new TServerException("数据异常");
		} else if (companyList.size() == 1) {
			// 更新游客信息
			PartnerInfoDto partnerDto = new PartnerInfoDto();
			partnerDto.setHigherid(companyList.get(0).getId());
			partnerDto.setId(userId);
			partnerDto.setUserRoleId(0L);
			// 插入部门数据
			DepartmentDto depart = new DepartmentDto();
			depart.setMerchantId(companyList.get(0).getId());
			depart.setParentId(Long.parseLong("0"));
			depart.setDelFlag(DelFlagEnum.UNDEL.getNo());
			List<Department> list = departmentDao.selectListByDto(depart);
			if (list.size() > 1) {
				throw new TServerException("数据异常");
			} else if (list.size() == 0) {
				throw new TServerException("数据异常");
			} else {
				partnerDto.setDeptId(list.get(0).getId());
			}
			partnerInfoService.update(partnerDto);
		} else {
			throw new TServerException("未找到匹配公司");
		}
		res.setResult(ResultEnum.SUCCESS.getNo());
		res.setResultMsg("操作成功");
		return res;
	}
	
	@Override
	public GetCompanyByUserIdResDto getCompanyByUserId(GetCompanyByUserIdReqDto reqDto) {
		GetCompanyByUserIdResDto res = new GetCompanyByUserIdResDto();
		if (null == reqDto.getHigherId()) {
			throw new TServerException("公司Id为空");
		}
		Company company = companyService.selectById(reqDto.getHigherId());
		DepartmentDto entity = new DepartmentDto();
		entity.setMerchantIds(String.valueOf(company.getId()));
		List<DepartmentDto> list = departmentDao.selectPrincipalNameByCompany(entity);
		if(CollectionUtils.isNotEmpty(list)){
			DepartmentDto departmentDto = list.get(0);
			res.setPrincipalName(departmentDto.getPrincipalName());
			res.setPrincipalPhone(departmentDto.getPrincipalPhone());
		}else{
			res.setPrincipalName(null);
			res.setPrincipalPhone(null);

		}
		res.setCompany(company);
		res.setResult(ResultEnum.SUCCESS.getNo());
		return res;
	}
	
	@Override
	public GetCompanyForCommissionRuleResDto getCompanyForCommissionRule(GetCompanyForCommissionRuleReqDto reqDto) {
		if (reqDto.getHigherId() == null) {
			throw new TServerException("人员公司id为空");
		}
		if (reqDto.getPremisesId() == null) {
			throw new TServerException("楼盘id为空");
		}
		GetCompanyForCommissionRuleResDto res = new GetCompanyForCommissionRuleResDto();
		List<CompanyRelationDto> cooperationList = companyService.findCompanysForCommissionRule(reqDto.getHigherId(), reqDto.getPremisesId());
		res.setCooperationList(cooperationList);
		res.setResult(ResultEnum.SUCCESS.getNo());
		return res;
	}
	
	@Override
	public GetDeptByIdResDto getDeptById(GetDeptByIdReqDto reqDto) {
		GetDeptByIdResDto resDto = new GetDeptByIdResDto();
		Department dept = departmentDao.selectById(Long.valueOf(reqDto.getId()));
		DepartmentDto deptDto = new DepartmentDto();
		BeanUtils.copyProperties(dept, deptDto);
		if(null != dept) {
			Company company = companyService.selectById(dept.getMerchantId());
			if(null != company) {
				deptDto.setProvince(company.getProvince());
				deptDto.setCity(company.getCity());
				deptDto.setAddress(company.getAdress());
				ModelInfo modelInfo = new ModelInfo();
				modelInfo.setRelId(company.getId());
				modelInfo.setModelType(ModelTypeEnum2.COMPANY.getNo());
				modelInfo.setModelName("营业执照");
				List<ModelInfo> modelInfoList = modelInfoService.selectListByDto(modelInfo);
				if(!CollectionUtils.isEmpty(modelInfoList)) {
					deptDto.setCredential(modelInfoList.get(0).getModelValue());
				}
			}
			
		}
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		resDto.setDepartment(deptDto);
		return resDto;
	}
	
	@Override
	public GetImportErrorMsgResDto getImportErrorMsg(GetImportErrorMsgReqDto reqDto) {
		GetImportErrorMsgResDto res = new GetImportErrorMsgResDto();
		ImportErrorDto entity = new ImportErrorDto();
		entity.setImportType(reqDto.getImportType());
		entity.setImpId(reqDto.getImpId());
		List<ImportError> impList = importErrorService.selectListByDto(entity);
		res.setImpList(impList);
		res.setResult(ResultEnum.SUCCESS.getNo());
		return res;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public AddAgentDeptResDto addAgentDept(AddAgentDeptReqDto reqDto) {
		AddAgentDeptResDto resDto = new AddAgentDeptResDto();
		resDto.setResult(ResultEnum.FAIL.getNo());
		try {
			Long merchantId;
			boolean regesitFlag = CheckStatusEnum.TODO.getNo().equals(reqDto.getStatus());
			Long companyId = null;
			PartnerInfo partnerInfo = null;
			if(!regesitFlag) {
				partnerInfo = partnerInfoService.selectById(Long.valueOf(reqDto.getUserId()));
				companyId = partnerInfo.getHigherid();
			}else {
				companyId = reqDto.getCompanyId();
			}
			CompanyDto companyDto = new CompanyDto();
			DepartmentDto departmentDto = new DepartmentDto();
			departmentDto.setParentId(reqDto.getParentId());
			if(Objects.isNull(reqDto.getParentId())){
				departmentDto.setLayer(0);
				departmentDto.setParentId(0L);
				//查询其开发商的是否默认佣金设置
				Company devCompany = companyService.selectById(companyId);
				companyDto.setCompanyName(reqDto.getCompanyName());
				//当新增第一级机构时，判断机构名称是否存在
				boolean flag = isExsitsCoo(companyDto, devCompany.getId());
				if(flag){
					resDto.setResultMsg("分销商名称已存在，请核实后重新输入");
					return resDto;
				}
				companyDto.setPrincipal(reqDto.getPrincipal());
				companyDto.setCompanyType(1L);
				companyDto.setAdress(reqDto.getAddress());
				companyDto.setProvince(reqDto.getProvince());
				companyDto.setCity(reqDto.getCity());
				companyDto.setChargeMan(reqDto.getChargeMan());
				companyDto.setPhone(reqDto.getPhone());
				companyDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
				companyDto.setCommissionFlag(devCompany.getCommissionFlag());
				companyDto.setMessageFlag(devCompany.getMessageFlag());
				// 历史情况，不存在，则默认是审核通过
				companyDto.setStatus(StringUtil.isNotNull(reqDto.getStatus())? reqDto.getStatus(): 
					CheckStatusEnum.SUCCESS.getNo());
				companyDto.setCreateTime(Calendar.getInstance().getTime());
				if(!regesitFlag) {
					companyDto.setCreateUserId(partnerInfo.getId());
				}else {
					companyDto.setCreateOrigin(CreateOriginEnum.WEAPP_REGESIT.getCode());
				}
				companyDto = companyService.create(companyDto);
				//更新新增机构的公司代码
				String companyCode = updateCompanyCode(companyDto);
				if(StringUtils.isNotBlank(companyCode)){
					companyDto.setCompanyCode(companyCode);
				}
				merchantId = companyDto.getId();

				//新增一级机构时，向楼盘关系表中绑定默认全部楼盘
				insertPremisesRelation(companyId,companyDto.getId());
				
				//合作机构与开发商绑定
				CompanyRelationDto crDto = new CompanyRelationDto();
				crDto.setDevCompany(companyId);
				crDto.setAgentCompany(merchantId);
				crDto.setRelationStatus(RelationStatusEnum.VALID.getNo());
				crDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
				if(!regesitFlag) {
					crDto.setCreateUserId(partnerInfo.getId());
				}
				companyRelationService.create(crDto);
				if(regesitFlag) {
					List<ModelInfo> modelInfoList = reqDto.getModelInfoList();
					if(!CollectionUtils.isEmpty(modelInfoList)) {
						for (ModelInfo modelInfo : modelInfoList) {
							modelInfo.setRelId(companyDto.getId());
							modelInfo.setModelType(ModelTypeEnum2.COMPANY.getNo());
						}
						modelInfoService.batchInsertModelInfo(modelInfoList);
					}
				}else {
					// 添加营业执照至自定义模板表, 删除以前的营业执照信息
					ModelInfo modelInfo = new ModelInfo();
					modelInfo.setRelId(companyDto.getId());
					modelInfo.setModelType(ModelTypeEnum2.COMPANY.getNo());
					modelInfo.setModelName("营业执照");
					modelInfo.setModelId(reqDto.getCredentialModelId());
					modelInfo.setModelValue(reqDto.getCredentialModelValue());
					modelInfoService.saveModelValue(modelInfo);
				}
				
			}else {
				Department department = departmentDao.selectById(reqDto.getParentId());
				merchantId = department.getMerchantId();
				if(Objects.nonNull(department.getLayer())){
					departmentDto.setLayer(department.getLayer() + 1);
				}
			}
			
			//开发商后台新增部门
			departmentDto.setDepartmentCode(String.valueOf(companyDto.getId()));
			departmentDto.setDepartmentName(reqDto.getCompanyName());
			departmentDto.setMerchantId(merchantId);
			departmentDto.setPrincipal(reqDto.getPrincipal());
			departmentDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			if(!regesitFlag) {
				departmentDto.setCreateUserId(partnerInfo.getId());
			}
			departmentDto.setCreateTime(Calendar.getInstance().getTime());
			departmentDao.create(departmentDto);

			if(Objects.nonNull(merchantId) && merchantId != 0){
				log.info("addAgentDept --> refresh company dept layer, because this dept layer is null: {}", JSONObject.toJSONString(reqDto));
				deptPermissionService.initDeptPermissionCode(merchantId);
			}
			
			if(!regesitFlag) {
				deptPermissionService.addPersonalDeptPermission(Long.valueOf(reqDto.getUserId()), partnerInfo.getUserRoleId(),
						partnerInfo.getHigherid(), departmentDto.getId());
			}
			
			resDto.setCompany(companyDto);
			resDto.setDeptId(departmentDto.getId());
			resDto.setResult(ResultEnum.SUCCESS.getNo());
			resDto.setResultMsg("操作成功!");
		}catch (Exception ex) {
			log.error("操作失败: {}", ex);
			resDto.setResultMsg("操作失败: " + ex.getMessage());
		}
		return resDto;
	}

	@Override
	public EditAgentDeptResDto editAgentDept(EditAgentDeptReqDto reqDto) {
		EditAgentDeptResDto resDto = new EditAgentDeptResDto();
		resDto.setResult(ResultEnum.FAIL.getNo());
		try {
			PartnerInfo partnerInfo = partnerInfoService.selectById(Long.valueOf(reqDto.getUserId()));
			Department dept = departmentDao.selectById(reqDto.getId());
			if(null == dept) {
				resDto.setResultMsg("部门不存在,请刷新后重试!");
				return resDto;
			}
			Company company = companyService.selectById(dept.getMerchantId());
			if(null == company) {
				resDto.setResultMsg("部门所在公司不存在,请刷新后重试!");
				return resDto;
			}
			//当部门为第一级机构时修改公司的省市及地址
			if(dept.getParentId()!=null&&0L==dept.getParentId()){
				CompanyDto companyDto = new CompanyDto();
				companyDto.setId(company.getId());
				companyDto.setCompanyName(reqDto.getCompanyName());
				companyDto.setAdress(reqDto.getAddress());
				companyDto.setProvince(reqDto.getProvince());
				companyDto.setCity(reqDto.getCity());
				companyService.update(companyDto);
				
				// 修改当前公司的营业执照的值
				// 添加营业执照至自定义模板表, 删除以前的营业执照信息
				ModelInfo modelInfo = new ModelInfo();
				modelInfo.setRelId(company.getId());
				modelInfo.setModelType(ModelTypeEnum2.COMPANY.getNo());
				modelInfo.setModelName("营业执照");
				modelInfo.setModelId(reqDto.getCredentialModelId());
				modelInfo.setModelValue(reqDto.getCredentialModelValue());
				modelInfoService.saveModelValue(modelInfo);
			}
			
			DepartmentDto departmentDto = new DepartmentDto();
			departmentDto.setId(reqDto.getId());
			departmentDto.setDepartmentName(reqDto.getCompanyName());
			departmentDto.setPrincipal(reqDto.getPrincipal());
			departmentDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			departmentDto.setUpdateUserId(partnerInfo.getId());
			departmentDao.update(departmentDto);
			resDto.setResult(ResultEnum.SUCCESS.getNo());
			resDto.setResultMsg("操作成功!");
		}catch(Exception ex) {
			log.error("操作失败: {}", ex);
			resDto.setResultMsg("操作失败: " + ex.getMessage());
		}
		return resDto;
	}

	/**
	*@description 合并部门
	*@author sangtao
	*@date 2017/12/20
	*@param dto
	**/
	@Override
	public MergeDeptResDto mergeDept(MergeDeptReqDto dto){
		MergeDeptResDto resDto = new MergeDeptResDto();

		Long mergeId = dto.getDeptId();
		Long acceptId = dto.getAcceptId();
		if("0".equals(dto.getDeptLevel())){
			throw new TServerException("顶级部门不能合并");
		}

		checkChildDept(dto.getDeptId(),dto.getAcceptId(),"不能合并到子部门");
		Department delDept = new Department();
		delDept.setDelFlag(DelFlagEnum.DEL.getNo());
		delDept.setId(mergeId);
		mapper.edit(delDept);
		//更新子部门到目标部门
		mapper.editParent(mergeId,acceptId);
		//3.更新人员表
		partnerInfoMapper.editParent(mergeId, acceptId);
		// 4、清空被合并部门人员的权限信息
		// 合并只会应先该机构权限,楼盘权限不用关心
		PartnerInfoDto piDto = new PartnerInfoDto();
		piDto.setDeptId(acceptId);
		List<PartnerInfo> partnerInfoList = partnerInfoService.selectListByDto(piDto);
		if(CollectionUtils.isNotEmpty(partnerInfoList)){
			PartnerInfo pi = partnerInfoList.get(0);
			dataPermissionService.cleanCompanyCacheByPartner(pi.getId());
		}
		Department department = mapper.selectById(mergeId);
		mapper.resetWeappQrcodeByPermissionCode(department);
		
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		resDto.setResultMsg("操作成功!");
		return resDto;
	}

	/**
	*@description 转移部门
	*@author sangtao
	*@date 2017/12/20
	*@param dto
	**/
	@Override
	public ChangeDeptResDto changeDept(ChangeDeptReqDto dto){
		ChangeDeptResDto resDto = new ChangeDeptResDto();
		Long mergeId = dto.getDeptId();
		Long acceptId = dto.getAcceptId();

		Department department = mapper.selectById(mergeId);
		if(department !=null && department.getParentId().equals(acceptId)){
			throw new TServerException("已经在该部门下，无法转移");
		}

		//本部机构不能加到顶级
		if("0".equals(dto.getDeptLevel())){
			throw new TServerException("顶级部门不能转移");
		}
		if(dto.getAcceptId().equals(dto.getDeptId())){
			throw new TServerException("不能转移到自己部门");
		}
		//不能转移到自己的子部门
		checkChildDept(dto.getDeptId(),dto.getAcceptId(),"不能转移到子部门");

		PartnerInfoDto piDto = new PartnerInfoDto();
		piDto.setDeptId(acceptId);
		List<PartnerInfo> partnerInfoList = partnerInfoService.selectListByDto(piDto);
		if(CollectionUtils.isNotEmpty(partnerInfoList)){
			PartnerInfo pi = partnerInfoList.get(0);
			dataPermissionService.cleanCompanyCacheByPartner(pi.getId());
		}

		//1.将部门parent转移到目标
		Department acceptDept = mapper.selectById(acceptId);
		Department dept = new Department();
		dept.setId(mergeId);
		if(Objects.nonNull(acceptDept.getLayer())){
			dept.setLayer(acceptDept.getLayer() + 1);
		}
		dept.setParentId(acceptId);
		mapper.edit(dept);

		// 把对应的部门分销小程序二维码置为空（当前转移的部门以及转移至的子部门）
//		mapper.resetWeappQrcodeByPermissionCode(department);
		
		// 变更会涉及到部门权限Code的变更,所有直接刷新此公司
		deptPermissionService.initDeptPermissionCode(acceptDept.getMerchantId());
		
		// 刷新权限
		deptPermissionService.cleanCompanyCacheByCompanyUuid(dto.getCompanyUuid());

		resDto.setResult(ResultEnum.SUCCESS.getNo());
		resDto.setResultMsg("操作成功!");
		return resDto;
	}

	@Override
	public ImportCooOrgResDto importCooOrg(ImportCooOrgReqDto reqDto) throws Exception {
		MultipartFile file = null;
		Iterator<String> fileNames = reqDto.getMulRequest().getFileNames();
		ImportCooOrgResDto res = new ImportCooOrgResDto();
		if (fileNames.hasNext()) {
			// 附件对应的参数名
			String fileName = fileNames.next();
			if (!isExcel(fileName)) {
				throw new TServerException("请选择正确的excel");
			}
			// 获取到附件
			file = reqDto.getMulRequest().getFile(fileName);
			if (file == null) {
				throw new TServerException("批量导入失败,请刷新页面后重试");
			}
			Long userId = Long.parseLong(reqDto.getUserId());
			PartnerInfo pi = partnerInfoService.selectById(userId);
			Company company = companyService.selectById(pi.getHigherid());
			Map<String, String> map = uploadExcelService.uploadCooOrgExcel(userId, company.getDomain(), file.getInputStream(), fileName);

			try{
				// 导入后刷新被导入机构的分销公司权限Code及部门层级
				// 此处捕获异常,防止因导入返回内容有误而导致导入失败
				String[] refreshCompanyIds = map.get("refreshCompanyIds").split(",");
				for(int ii=0; ii<refreshCompanyIds.length; ii++){
					if(StringUtils.isNotBlank(refreshCompanyIds[ii])){
						deptPermissionService.initDeptPermissionCode(Long.valueOf(refreshCompanyIds[ii]));
					}
				}
			}catch (Exception ex){
				log.error("import agent company error: {}", ex);
			}

			res.setResult(map.get("result"));
			res.setResultMsg(map.get("msg"));
			if ("1".equals(map.get("result"))) {
				res.setUuid(map.get("data"));
			}
		} else {
			// 读取文件失败
			res.setResult(ResultEnum.FAIL.getNo());
			res.setResultMsg("批量导入失败");
		}
		return res;
	}

	/**
	 * 根据当前部门获取部门关系
	 * @param getParentDeptReqDto
	 * @return
	 */
	@Override
	public GetParentDeptResDto getParentDeptBySubDept(GetParentDeptReqDto getParentDeptReqDto){
		Long merchantId = getParentDeptReqDto.getMerchantId();
		Long deptId = getParentDeptReqDto.getDeptId();
		if(merchantId == null || deptId == null) return null;

		GetParentDeptResDto getParentDeptResDto = new GetParentDeptResDto();
		DepartmentDto departmentDto = new DepartmentDto();
		departmentDto.setMerchantId(merchantId);
		departmentDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		List<Department> tempList = mapper.selectListByDto(departmentDto);
		Map<Long,Department> map = tempList.stream().collect(Collectors.toMap(Department::getId, Function.identity()));

		Department selfDept = map.get(deptId);
		getParentDeptResDto.setOrgId(merchantId);
		if(selfDept == null) {
			return getParentDeptResDto;
		}
		if(Objects.nonNull(selfDept) && map.containsKey(selfDept.getParentId())){
			Department parentDept1 = map.get(selfDept.getParentId());

			if(map.containsKey(parentDept1.getParentId())){
				Department parentDept2 = map.get(parentDept1.getParentId());

				getParentDeptResDto.setOrgName(parentDept2.getDepartmentName());

				getParentDeptResDto.setStoreId(parentDept1.getId());
				getParentDeptResDto.setStoreName(parentDept1.getDepartmentName());

				getParentDeptResDto.setGroupId(selfDept.getId());
				getParentDeptResDto.setGroupName(selfDept.getDepartmentName());
			}else{
				getParentDeptResDto.setOrgName(parentDept1.getDepartmentName());

				getParentDeptResDto.setStoreId(selfDept.getId());
				getParentDeptResDto.setStoreName(selfDept.getDepartmentName());
			}
		}else{
			//顶级部门
			getParentDeptResDto.setOrgName(selfDept.getDepartmentName());
		}
		return getParentDeptResDto;
	}

	private void checkChildDept(Long deptId,Long acceptId,String msg){
		DepartmentDto departmentDto = new DepartmentDto();
		departmentDto.setParentId(deptId);
		List<DepartmentDto> list = mapper.selectList(departmentDto);
		for (DepartmentDto dto : list) {
			if (dto.getId().equals(acceptId)) {
				throw new TServerException(msg);
			} else {
				checkChildDept(dto.getId(),acceptId,msg);
			}
		}
	}

	@Override
	public ImportCooOrgResDto importPremises(ImportCooOrgReqDto reqDto) throws Exception {
		MultipartFile file = null;
		Iterator<String> fileNames = reqDto.getMulRequest().getFileNames();
		ImportCooOrgResDto res = new ImportCooOrgResDto();
		if (fileNames.hasNext()) {
			// 附件对应的参数名
			String fileName = fileNames.next();
//			if (!isExcel(fileName)) {
//				throw new TServerException("请选择正确的excel");
//			}
			// 获取到附件
			file = reqDto.getMulRequest().getFile(fileName);
			if (file == null) {
				throw new TServerException("批量导入失败,请刷新页面后重试");
			}
			Long userId = Long.parseLong(reqDto.getUserId());
			PartnerInfo pi = partnerInfoService.selectById(userId);
			//Company company = companyService.selectById(pi.getHigherid());
			Map<String, String> map = uploadExcelService.uploadExcelPremise(reqDto.getCompanyUuid(), userId, file.getInputStream(), fileName);
			res.setResult(map.get("result"));
			res.setResultMsg(map.get("msg"));
			if ("1".equals(map.get("result"))) {
				res.setUuid(map.get("data"));
			}
		} else {
			// 读取文件失败
			res.setResult(ResultEnum.FAIL.getNo());
			res.setResultMsg("批量导入失败");
		}
		return res;
	}

	@Override
	public ImportCooOrgResDto importPremiseHouseType(ImportCooOrgReqDto reqDto) throws Exception {
		MultipartFile file = null;
		Iterator<String> fileNames = reqDto.getMulRequest().getFileNames();
		ImportCooOrgResDto res = new ImportCooOrgResDto();
		if (fileNames.hasNext()) {
			// 附件对应的参数名
			String fileName = fileNames.next();
//			if (!isExcel(fileName)) {
//				throw new TServerException("请选择正确的excel");
//			}
			// 获取到附件
			file = reqDto.getMulRequest().getFile(fileName);
			if (file == null) {
				throw new TServerException("批量导入失败,请刷新页面后重试");
			}
			Long userId = Long.parseLong(reqDto.getUserId());
			//PartnerInfo pi = partnerInfoService.selectById(userId);
			//Company company = companyService.selectById(pi.getHigherid());
			Map<String, String> map = uploadExcelService.uploadExcelPremiseHouseType(reqDto.getCompanyUuid(), file.getInputStream(), fileName);
			res.setResult(map.get("result"));
			res.setResultMsg(map.get("msg"));
			if ("1".equals(map.get("result"))) {
				res.setUuid(map.get("data"));
			}
		} else {
			// 读取文件失败
			res.setResult(ResultEnum.FAIL.getNo());
			res.setResultMsg("批量导入失败");
		}
		return res;
	}

	@Override
	public ImportCooOrgResDto importPremiseDynamic(ImportCooOrgReqDto reqDto) throws Exception {
		MultipartFile file = null;
		Iterator<String> fileNames = reqDto.getMulRequest().getFileNames();
		ImportCooOrgResDto res = new ImportCooOrgResDto();
		if (fileNames.hasNext()) {
			// 附件对应的参数名
			String fileName = fileNames.next();
//			if (!isExcel(fileName)) {
//				throw new TServerException("请选择正确的excel");
//			}
			// 获取到附件
			file = reqDto.getMulRequest().getFile(fileName);
			if (file == null) {
				throw new TServerException("批量导入失败,请刷新页面后重试");
			}
			Long userId = Long.parseLong(reqDto.getUserId());
			//PartnerInfo pi = partnerInfoService.selectById(userId);
			//Company company = companyService.selectById(pi.getHigherid());
			Map<String, String> map = uploadExcelService.uploadExcelPremiseDynamic(reqDto.getCompanyUuid(), file.getInputStream(), fileName);
			res.setResult(map.get("result"));
			res.setResultMsg(map.get("msg"));
			if ("1".equals(map.get("result"))) {
				res.setUuid(map.get("data"));
			}
		} else {
			// 读取文件失败
			res.setResult(ResultEnum.FAIL.getNo());
			res.setResultMsg("批量导入失败");
		}
		return res;
	}

	@Override
	public ImportCooOrgResDto importPremiseImage(ImportCooOrgReqDto reqDto) throws Exception {
		MultipartFile file = null;
		Iterator<String> fileNames = reqDto.getMulRequest().getFileNames();
		ImportCooOrgResDto res = new ImportCooOrgResDto();
		if (fileNames.hasNext()) {
			// 附件对应的参数名
			String fileName = fileNames.next();
//			if (!isExcel(fileName)) {
//				throw new TServerException("请选择正确的excel");
//			}
			// 获取到附件
			file = reqDto.getMulRequest().getFile(fileName);
			if (file == null) {
				throw new TServerException("批量导入失败,请刷新页面后重试");
			}
			Long userId = Long.parseLong(reqDto.getUserId());
			//PartnerInfo pi = partnerInfoService.selectById(userId);
			//Company company = companyService.selectById(pi.getHigherid());
			Map<String, String> map = uploadExcelService.uploadExcelPremiseImage(reqDto.getCompanyUuid(), file.getInputStream(), fileName);
			res.setResult(map.get("result"));
			res.setResultMsg(map.get("msg"));
			if ("1".equals(map.get("result"))) {
				res.setUuid(map.get("data"));
			}
		} else {
			// 读取文件失败
			res.setResult(ResultEnum.FAIL.getNo());
			res.setResultMsg("批量导入失败");
		}
		return res;
	}

	@Override
	public ImportCooOrgResDto importPremiseCommission(ImportCooOrgReqDto reqDto) throws Exception {
		MultipartFile file = null;
		Iterator<String> fileNames = reqDto.getMulRequest().getFileNames();
		ImportCooOrgResDto res = new ImportCooOrgResDto();
		if (fileNames.hasNext()) {
			// 附件对应的参数名
			String fileName = fileNames.next();
//			if (!isExcel(fileName)) {
//				throw new TServerException("请选择正确的excel");
//			}
			// 获取到附件
			file = reqDto.getMulRequest().getFile(fileName);
			if (file == null) {
				throw new TServerException("批量导入失败,请刷新页面后重试");
			}
			Long userId = Long.parseLong(reqDto.getUserId());
			//PartnerInfo pi = partnerInfoService.selectById(userId);
			//Company company = companyService.selectById(pi.getHigherid());
			Map<String, String> map = uploadExcelService.uploadExcelPremiseCommission(reqDto.getCompanyUuid(), file.getInputStream(), fileName);
			res.setResult(map.get("result"));
			res.setResultMsg(map.get("msg"));
			if ("1".equals(map.get("result"))) {
				res.setUuid(map.get("data"));
			}
		} else {
			// 读取文件失败
			res.setResult(ResultEnum.FAIL.getNo());
			res.setResultMsg("批量导入失败");
		}
		return res;
	}

}
